import Node from "./Node";

export default class CircularLink{
    public head: Node | null = null;
    public length = 0;
    public findLast():Node|null{
        let curNode = this.head as Node;
        if(curNode == undefined){
            return null;
        }
        while(curNode.next != this.head){
            curNode = curNode.next as Node;
        }
        return curNode;
    }
    public insert(value:any):Node{
        let node = new Node(value)
        if(!this.head){
            this.head = node;
            this.head.next = node;
        } else {
            node.next = this.head;
            let lastNode = this.findLast() as Node;
            lastNode.next = node;
        }
        this.length ++;
        return node;
    }
    public find(value:any):Node|null{
        if(!this.head){
            return null;
        }
        let curNode:Node | null = this.head as Node;
        while(curNode.value != value){
            curNode = curNode.next as Node;
            if(curNode == this.head){
                curNode = null;
                break;
            }
        }
        return curNode;
    }
    public forEach(callback:(c:Node|null)=>void){
        if(!this.head){
            return;
        }
        let curNode = this.head;
        callback(curNode);
        while(curNode.next != this.head){
            curNode = curNode.next as Node;
            callback(curNode);
        }
    }
    public size(){
        return this.length;
    }
}